﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.IO;

namespace XUtility
{
    public class IniConfig
    {
        public static string FilePath; //INI文件名 
                                       //声明读写INI文件的API函数 
        [DllImport("kernel32")]
        public static extern bool WritePrivateProfileString(byte[] section, byte[] key, byte[] val, string filePath);[DllImport("kernel32")]
        public static extern int GetPrivateProfileString(byte[] section, byte[] key, byte[] def, byte[] retVal, int size, string filePath);//与ini交互必须统一编码格式
        private static byte[] getBytes(string s, string encodingName)
        {
            return null == s ? null : Encoding.GetEncoding(encodingName).GetBytes(s);
        }
        public static string ReadString(string section, string key, string def, string fileName, string encodingName = "utf-8", int size = 1024)
        {
            byte[] buffer = new byte[size];
            int count = GetPrivateProfileString(getBytes(section, encodingName), getBytes(key, encodingName), getBytes(def, encodingName), buffer, size, fileName);
            return Encoding.GetEncoding(encodingName).GetString(buffer, 0, count).Trim();
        }

        /// <summary>
        /// 类的构造函数，传递INI文件名 
        /// </summary>
        /// <param name="AFileName"></param>
        public static void SetFilePath(string AFileName)
        {
            // 判断文件是否存在 
            FileInfo fileInfo = new FileInfo(AFileName);
            //Todo:搞清枚举的用法 
            if ((!fileInfo.Exists))
            { //|| (FileAttributes.Directory in fileInfo.Attributes)) 
                //文件不存在，建立文件 
                System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
                try
                {
                    sw.Write("系统配置文件");
                    sw.Close();
                }
                catch
                {
                    throw (new ApplicationException("Ini文件不存在"));
                }
            }
            //必须是完全路径，不能是相对路径 
            FilePath = fileInfo.FullName;
        }

        /// <summary>
        /// 写INI文件 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        public static void WriteString(string Section, string key, string Value, string encodingName = "utf-8")
        {
            var re= WritePrivateProfileString(getBytes(Section, encodingName), getBytes(key, encodingName), getBytes(Value, encodingName), FilePath);

            if (!re)
            {
                // Todo:抛出自定义的异常 
                throw (new ApplicationException("写Ini文件出错"));
            }
        }

        /// <summary>
        /// 读取INI文件指定 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="key"></param>
        /// <param name="Default"></param>
        /// <returns></returns>
        public static string ReadString(string Section, string key, string Default="", string encodingName = "utf-8", int size = 1024)
        {
            byte[] buffer = new byte[size];
            int count = GetPrivateProfileString(getBytes(Section, encodingName), getBytes(key, encodingName), getBytes(Default, encodingName), buffer, size, FilePath);
            return Encoding.GetEncoding(encodingName).GetString(buffer, 0, count).Trim();

            //Byte[] Buffer = new Byte[65535];
            //int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FilePath);
            ////必须设定0（系统默认的代码页）的编码方式，否则无法支持中文 
            //string s = Encoding.GetEncoding(0).GetString(Buffer);
            //s = s.Substring(0, bufLen);
            //return s.Trim();
        }

        /// <summary>
        /// 读整数 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Ident"></param>
        /// <param name="Default"></param>
        /// <returns></returns>
        public static int ReadInteger(string Section, string Ident, int Default)
        {
            string intStr = ReadString(Section, Ident, Convert.ToString(Default));
            try
            {
                return Convert.ToInt32(intStr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }

        /// <summary>
        /// 写整数 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Ident"></param>
        /// <param name="Value"></param>
        public static void WriteInteger(string Section, string Ident, int Value)
        {
            WriteString(Section, Ident, Value.ToString());
        }

        /// <summary>
        /// 读布尔 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Ident"></param>
        /// <param name="Default"></param>
        /// <returns></returns>
        public static bool ReadBool(string Section, string Ident, bool Default)
        {
            try
            {
                return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }

        /// <summary>
        /// 写Bool 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Ident"></param>
        /// <param name="Value"></param>
        public static void WriteBool(string Section, string Ident, bool Value)
        {
            WriteString(Section, Ident, Convert.ToString(Value));
        }

        /// <summary>
        /// 从Ini文件中，将指定的Section名称中的所有Ident添加到列表中 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Idents"></param>
        public static void ReadSection(string Section, StringCollection Idents, string encodingName = "utf-8")
        {
            Byte[] Buffer = new Byte[16384];
            //Idents.Clear(); 

            int bufLen = GetPrivateProfileString(getBytes(Section, encodingName), null, null, Buffer, Buffer.GetUpperBound(0),
              FilePath);
            //对Section进行解析 
            GetStringsFromBuffer(Buffer, bufLen, Idents);
        }

        private static void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
        {
            Strings.Clear();
            if (bufLen != 0)
            {
                int start = 0;
                for (int i = 0; i < bufLen; i++)
                {
                    if ((Buffer[i] == 0) && ((i - start) > 0))
                    {
                        String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
                        Strings.Add(s);
                        start = i + 1;
                    }
                }
            }
        }

        /// <summary>
        /// 从Ini文件中，读取所有的Sections的名称 
        /// </summary>
        /// <param name="SectionList"></param>
        public static void ReadSections(StringCollection SectionList)
        {
            //Note:必须得用Bytes来实现，StringBuilder只能取到第一个Section 
            byte[] Buffer = new byte[65535];
            int bufLen = 0;
            bufLen = GetPrivateProfileString(null, null, null, Buffer,
              Buffer.GetUpperBound(0), FilePath);
            GetStringsFromBuffer(Buffer, bufLen, SectionList);
        }

        /// <summary>
        /// 读取指定的Section的所有Value到列表中 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Values"></param>
        public static void ReadSectionValues(string Section, NameValueCollection Values)
        {
            StringCollection KeyList = new StringCollection();
            ReadSection(Section, KeyList);
            Values.Clear();
            foreach (string key in KeyList)
            {
                Values.Add(key, ReadString(Section, key, ""));
            }
        }

        /// <summary>
        /// 清除某个Section 
        /// </summary>
        /// <param name="Section"></param>
        public static void EraseSection(string Section, string encodingName = "utf-8")
        {
            // 
            if (!WritePrivateProfileString(getBytes(Section, encodingName), null, null, FilePath))
            {
                throw (new ApplicationException("无法清除Ini文件中的Section"));
            }
        }

        /// <summary>
        /// 删除某个Section下的键 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="key"></param>
        public static void DeleteKey(string Section, string key, string encodingName = "utf-8")
        {
            WritePrivateProfileString(getBytes(Section, encodingName), getBytes(key, encodingName), null, FilePath);
        }
        //Note:对于Win9X，来说需要实现UpdateFile方法将缓冲中的数据写入文件 
        //在Win NT, 2000和XP上，都是直接写文件，没有缓冲，所以，无须实现UpdateFile 
        //执行完对Ini文件的修改之后，应该调用本方法更新缓冲区。 
        public static void UpdateFile()
        {
            WritePrivateProfileString(null, null, null, FilePath);
        }

        /// <summary>
        /// 检查某个Section下的某个键值是否存在 
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Ident"></param>
        /// <returns></returns>
        public static bool ValueExists(string Section, string Ident)
        {
            // 
            StringCollection Idents = new StringCollection();
            ReadSection(Section, Idents);
            return Idents.IndexOf(Ident) > -1;
        }
    }
}
